package org.example.JVM.ByteCode.Handler;

import org.example.JVM.ByteCode.Type.ClassFile;
import org.example.JVM.ByteCode.Type.U4;

import java.nio.ByteBuffer;

/**
 * @description:魔数解析器，四字节，固定值为0xFAFEBABE
 * @author: farprt
 * @create: 2022-11-13 13:48
 **/
public class MagicHandler implements BaseByteCodeHandler{

    /**
     * @param
     * @return: {@link int}
     * @Author: farprt
     * @date: 2022/11/13 14:08
     * @description: 排序在第一个
     */
    @Override
    public int order() {
        return 0;
    }

    /**
     * @param codeBuf
     * @param classFile
     * @return:
     * @Author: farprt
     * @date: 2022/11/13 14:09
     * @description: 魔数占四个字节,连续读取四个字节并转为U4对象
     */
    @Override
    public void read(ByteBuffer codeBuf, ClassFile classFile) throws Exception {
        classFile.setMagic(new U4(codeBuf.get(),codeBuf.get(),codeBuf.get(),codeBuf.get()));
        if(!"0xCAFEBABE".equalsIgnoreCase(classFile.getMagic().toHexString())){
            throw new Exception("not a class file!");
        }
    }
}